<?php

namespace App\Livewire;

use App\Models\Video;
use Illuminate\Support\Collection;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class VideoShow extends Component
{
    use WithPagination;

    public Video $video;

    public int $perPage = 4;

    public int $page = 1;

    public Collection $collection;

    public bool $hasMorePages;

    #[Url]
    public string $version = '';

    public function mount(): void
    {
        $this->collection = Collection::make();

        $this->loadMore();
    }

    public function loadMore(): void
    {
        $collection = Video::query()
            ->whereFullText('title', $this->video->title)
            ->where('id', '!=', $this->video->getKey())
            ->latest()
            ->simplePaginate(perPage: 10, page: $this->page);

        $this->collection->push(...$collection->items());

        if ($this->hasMorePages = $collection->hasMorePages()) {
            $this->page++;
        }
    }

    public function render()
    {
        return view('livewire.video-show');
    }

    #[Computed]
    public function currentPlay(): object
    {
        $version = $this->video->videos->first(function ($v) {
            if ($this->version) {
                return $v['fields']['id'] === $this->version;
            }

            return true;
        });

        return (object) $version['fields'];
    }
}
